<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/12/3
 * Time: 18:01
 */

namespace Api\Domain;


use Admin\Api\ConfigApi;
use Api\Model\ErrorCodeModel;
use Api\Vendor\BoyeUtils\BoyeUtils;

class BaseDomain {

    protected $notify_id;
    protected $client_id;
    protected $request_api_ver;
    protected $cur_api_ver;
    protected $domain_class;



    public function __construct(){
        $this->notify_id = $_POST['notify_id'];
        $this->client_id = $_POST['client_id'];
        $this->domain_class = $_POST['domain_class'];
        $this->request_api_ver = intval($_POST['api_ver']);
    }

    protected function checkVersion($version){

        if(is_array($version)){
            $legal = false;
            foreach($version as $item){

                if($item == intval($this->request_api_ver)){
                    $legal = true;
                    break;
                }

            }

            if($legal == false){
                $msg = "请更新客户端接口";
                $this->apiReturnErr($msg,ErrorCodeModel::Api_Need_Update);
            }

        }else{

            if($version != $this->request_api_ver){
                $msg = "请更新客户端接口,最新版本:".$version;
                $this->apiReturnErr($msg,ErrorCodeModel::Api_Need_Update);
            }
        }

    }

    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @param int $json_option 传递给json_encode的option参数
     * @return void
     */
    protected function ajaxReturn($data,$type='',$json_option=0) {
        $code = $data['code'];
        if($code == 0){
            $type = "T";
        }else{
            $type = "F";
        }

        $data = BoyeUtils::encrypt($data);
        $now = time();

        $param = array(
            'client_id'=>$this->client_id,
            'data'=>$data,
            'notify_id'=>$this->notify_id,
            'time'=>strval($now),
            'type'=>$type,
            'alg'=>'md5',
        );

        $param['sign'] = BoyeUtils::sign($param);

        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($param,$json_option));
    }

    /**
     * ajax返回
     * @param $data
     * @internal param $i
     */
    protected function apiReturnSuc($data){

        addLog($this->domain_class,$this->request_api_ver,$data,'返回成功',true);
        $this->ajaxReturn(array('code'=>0,'data'=>$data,'notify_id'=>$this->notify_id),"json");
    }

    /**
     * ajax返回，并自动写入token返回
     * @param $data
     * @param int $code
     * @internal param $i
     */
    protected function apiReturnErr($data,$code=-1){
        addLog($this->domain_class,$code,$data,'返回错误');
        $this->ajaxReturn(array('code'=>$code,'data'=>$data,'notify_id'=>$this->notify_id),"json");
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _post($key,$default='',$emptyErrMsg=''){
        $value = I("post._data_".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg,ErrorCodeModel::Lack_Parameter);
        }
        $value = $this->escapeEmoji($value);
        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg,ErrorCodeModel::Lack_Parameter);
        }
        return $value;
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _get($key,$default='',$emptyErrMsg=''){
        $value = I("get.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg,ErrorCodeModel::Lack_Parameter);
        }
        return $value;
    }

    /**
     * 从数据库中取得配置信息
     */
    protected function getConfig() {
        $config = S('global_config');
        //dump($config);
        if ($config === false) {
            $map = array();
            $fields = 'type,name,value';
            $result = apiCall(ConfigApi::QUERY_NO_PAGING, array($map, false, $fields));
            if ($result['status']) {
                $config = array();

                if (is_array($result['info'])) {
                    foreach ($result['info'] as $value) {
                        $config[$value['name']] = $this -> parse($value['type'], $value['value']);

                    }
                }
                //缓存配置300秒
                S("global_config", $config, 300);
            } else {
                LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                $this -> error($result['info']);
            }
        }
        //dump(session_id());

        //dump($config);
        C($config);
    }

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     * @return array|string
     */
    private static function parse($type, $value) {
        switch ($type) {
            case 3 :
                //解析数组
                $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
                if (strpos($value, ':')) {
                    $value = array();
                    foreach ($array as $val) {
                        list($k, $v) = explode(':', $val,2);
                        $value[$k] = $v;
                    }
                } else {
                    $value = $array;
                }
                break;
        }
        return $value;
    }

    /**
     *
     * @param $result
     * @param bool $cantBeNull
     * @param string $whenNullMsg 当为空时的信息
     */
    protected function checkApiCallResult($result,$cantBeNull=true,$whenNullMsg="获取信息为空!"){

        if(!$result['status']){
            $this->apiReturnErr($result['info']);
        }

        if($cantBeNull && is_null($result['info'])){
            $this->apiReturnErr($whenNullMsg);
        }

    }

    /**
     * @brief 干掉emoji
     * @autho chenjinya@baidu.com
     * @param {String} $strText
     * @return {String} removeEmoji
     **/
    protected function escapeEmoji($strText,$bool = false) {
        $preg =  '/\\\ud([8-9a-f][0-9a-z]{2})/i';
        if ($bool == true) {
            $boolPregRes = (preg_match($preg,json_encode($strText,true)));
            return $boolPregRes;
        } else {
            $strPregRes = (preg_replace($preg,'',json_encode($strText,true)));
            $strRet = json_decode($strPregRes,true);
            if(strlen($strRet)==0){
                return "";
            }
            return $strRet;
        }
    }
}